package network.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class EchoClient {
    private Socket socket;

    public EchoClient(String serverIP,int serverPort) throws IOException {
        //在new这个对象的时候，就涉及到“建立连接操作了”
        //由于连接建立好了之后，服务器信息就在操作系统中被TCp协议记录了，我们在应用程序层面上就不需要保存IP和端口
        socket = new Socket(serverIP,serverPort);
        // socket = new Socket();
        // socket.connect(serverIP,serverPort);
    }

    public void start() throws IOException{ 
        System.out.println("客户端启动");

        Scanner scanner = new Scanner(System.in);

        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
                Scanner scannerNet = new Scanner(inputStream);
                PrintWriter writer = new PrintWriter(outputStream);
            while (true) {
                //1.从控制台读取用户的输入
                System.out.print("> ");
                String request = scanner.next();
                //2.构造请求发送给服务器
                writer.println(request);
                //刷新缓冲区
                writer.flush();
                //3.读取服务器的响应
                if (!scannerNet.hasNext()) {
                    System.out.println("server disconnect");
                    break;
                }
                String response = scannerNet.next();
                //4.把响应显示到控制台
                System.out.println(response);

            }
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            socket.close();
        }
        
    }
    public static void main(String[] args) throws IOException {
        EchoClient echoClient = new EchoClient("127.0.0.1", 9090);
        echoClient.start();
    }
}
